package com.newcapec.org.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.google.code.kaptcha.Constants;
import com.newcapec.org.demo.dao.UserInfoDao;
import com.newcapec.org.demo.entity.Result;
import com.newcapec.org.demo.entity.UserInfoEntity;
import com.newcapec.org.demo.service.UserInfoService;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

//servlet----tomcat(servlet)
//IOC容器(核心非常重要)
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @GetMapping("/selectAll")
    public List<UserInfoEntity> selectAll(UserInfoEntity userInfoEntity){
        return userInfoService.selectAll(userInfoEntity);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize")Integer pageSize,UserInfoEntity userInfoEntity){
        Result result = new Result();
        result.setCode(0);
        result.setData(userInfoService.selectByPage(pageNum,pageSize,userInfoEntity));
        return result;
    }



    @GetMapping("/selectById/{userId}")
    public Result<UserInfoEntity> selectById(@PathVariable("userId")Integer userId){
        Result<UserInfoEntity> result = new Result<>();

        UserInfoEntity user = userInfoService.selectById(userId);
        result.setData(user);
        return result;
    }

    @PostMapping("/login")
    public Result<UserInfoEntity> login(String userName, String userPwd, String virifyCode, HttpServletRequest request){
        Result result = new Result();
        String sessionCode = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
        if(!virifyCode.equalsIgnoreCase(sessionCode)){
            result.setCode(500);
            result.setMsg("验证码错误");
            return result;
        }


        UserInfoEntity user = userInfoService.login(userName,userPwd);
        if(user == null){
            result.setCode(500);
            result.setMsg("帐号错误");
            return result;
        }

        result.setCode(200);
        result.setMsg("登录成功");
        result.setData(user);
        request.getSession().setAttribute("userInfo",user);
        return result;
    }

    @PostMapping("/insert")
    public Result insert(UserInfoEntity userInfoEntity){
        Result result = new Result();
        if(userInfoService.insert(userInfoEntity)){
            result.setCode(200);
        }
        return  result;
    }


    @DeleteMapping("/batchDelete")
    public Result batchDelete(Integer[] userIds){

        Result result = new Result();
        if(userInfoService.batchDelete(userIds)){
            result.setCode(200);
        }
        return  result;
    }

    @PutMapping("/update")
    public Result update(UserInfoEntity userInfoEntity){
        Result result = new Result();
        if(userInfoService.update(userInfoEntity)){
            result.setCode(200);
            result.setMsg("更新成功");
        }else{
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }

    @PostMapping("/importExcel")
    public Result importExcel(HttpServletRequest request){
        Result result = new Result();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(false);
            try {
                List<UserInfoEntity> list = ExcelImportUtil.importExcel(file.getInputStream(), UserInfoEntity.class, params);
                boolean flag = userInfoService.saveBatch(list);
                if(flag){
                    result.setCode(200);
                    result.setMsg("导入成功");
                }else{
                    result.setCode(500);
                    result.setMsg("导入失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("导入失败");

            }
        }
        return result;
    }

    @GetMapping("/export")
    public void export(UserInfoEntity userInfoEntity,HttpServletResponse response) throws IOException {
        List<UserInfoEntity> list = userInfoService.selectAll(userInfoEntity);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","导出人:***","学生"),
                 UserInfoEntity.class, list);

        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户信息.xls", "UTF-8"));

        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
    }

}
